package com.laoniu.filter;

import com.alibaba.fastjson.JSONObject;
import com.laoniu.entity.SecurityUser;
import com.laoniu.service.RedisService;
import com.laoniu.service.sys.UserService;
import com.laoniu.utils.JwtUtils;
import com.laoniu.utils.RedisKeyUtils;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter{
    @Resource
    private UserService userService;
    @Autowired
    private RedisService redisService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if (StringUtils.isBlank(token)){
            //token为空的话, 就不管它, 让SpringSecurity中的其他过滤器处理请求
            //请求放行
            filterChain.doFilter(request, response);
            return;
        }
        //token不为空时, 解析token
        Claims claims = JwtUtils.parseJWT(token);
        Long userId = claims.get("userId", Long.class);
        String userStr = redisService.get(RedisKeyUtils.LOGIN_USER_KEY + userId);
        SecurityUser securityUser = JSONObject.parseObject(userStr, SecurityUser.class);
        if (Objects.isNull(securityUser)){
            throw new RuntimeException("用户未登录");
        }
        //更新缓存
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(securityUser, null, null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //放行
        filterChain.doFilter(request, response);
    }
}
